import simplejson
from django.shortcuts import render, redirect
from . import getStockInfo, index_search, analysis as ana, global_variable, show_detail, getweb, \
    attention_stock as att_stock
from django.http import HttpResponse, JsonResponse
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
from django.core import serializers
from functools import wraps

try:
    hour_t = '18,22'
    minute_t = '00'
    second_t = '0'
    # 实例化调度器
    scheduler = BackgroundScheduler()
    # 调度器使用DjangoJobStore()
    scheduler.add_jobstore(DjangoJobStore(), "default")


    # 'cron'方式循环，周一到周五day_of_week='mon-fri'，每天22:30:00执行,id为工作ID作为标记
    # @register_job(scheduler, 'cron', day_of_week='mon-sun', hour=hour_t, minute=minute_t, second=second_t,id='pre_analysis')
    @register_job(scheduler, 'cron', day_of_week='mon-fri', hour=hour_t, minute=minute_t, id='pre_analysis')  # 每天自动更新
    def test_job():
        print(getStockInfo.get_all_stock_daily_info())
        print(getStockInfo.get_all_stock_daily_basic_info())
        print(getStockInfo.get_all_block_trade_info())
        print(getStockInfo.get_all_moneyflow_info())
        ana.pre_analysis_db()  # 初始化数据，之前应该要执行数据更新


    # 监控任务
    register_events(scheduler)
    # 调度器开始
    scheduler.start()
except Exception as e:
    print(e)
    scheduler.shutdown()


# 说明：这个装饰器的作用，就是在每个视图函数被调用时，都验证下有没法有登录，
# 如果有过登录，则可以执行新的视图函数，
# 否则没有登录则自动跳转到登录页面。
def check_login(f):
    @wraps(f)
    def inner(request, *arg, **kwargs):
        if request.session.get('is_login') == '20180114':
            return f(request, *arg, **kwargs)
        else:
            return redirect('/')

    return inner


def login(request):
    # 如果是POST请求，则说明是点击登录按扭 FORM表单跳转到此的，那么就要验证密码，并进行保存session
    if request.method == "POST":

        username = request.POST.get('username')
        password = request.POST.get('password')

        if (username == 'ypy') and (password == '123'):
            # 登录成功
            # 1，生成特殊字符串
            # 2，这个字符串当成key，此key在数据库的session表（在数据库存中一个表名是session的表）中对应一个value
            # 3，在响应中,用cookies保存这个key ,(即向浏览器写一个cookie,此cookies的值即是这个key特殊字符）
            request.session['is_login'] = '20180114'  # 这个session是用于后面访问每个页面（即调用每个视图函数时要用到，即判断是否已经登录，用此判断）
            # request.session['username']=username  # 这个要存储的session是用于后面，每个页面上要显示出来，登录状态的用户名用。
            # 说明：如果需要在页面上显示出来的用户信息太多（有时还有积分，姓名，年龄等信息），所以我们可以只用session保存user_id
            request.session['user_id'] = 'sl'
            return redirect('/stock/index/')
    # 如果是GET请求，就说明是用户刚开始登录，使用URL直接进入登录页面的

    return render(request, "stock/login.html")


@check_login
def index(request):
    """
    index页面导航栏功能区函数
    :param request:
    :return:
    """

    if (request.method == "GET"):
        if request.is_ajax():
            # 更新数据菜单
            if (request.GET.get("cmd_class") == "update"):
                command = request.GET.getlist("command")
                if (command[0] == 'update_daily'):  result = getStockInfo.get_all_stock_daily_info()
                if (command[0] == 'update_daily_basic'): result = getStockInfo.get_all_stock_daily_basic_info()
                if (command[0] == 'update_block_trade'): result = getStockInfo.get_all_block_trade_info()
                if (command[0] == 'update_moneyflow'): result = getStockInfo.get_all_moneyflow_info()
                if (command[0] == 'update_stockbasic'): result = getStockInfo.update_stockbasic()
                if (command[0] == 'update_company'): result = getStockInfo.update_company_info()
                if (command[0] == 'update_all_basic'): result = getStockInfo.get_all_info()
                # 更新分析数据，加快页面载入速度
                if (command[0] == 'initial_analysis'): result = ana.pre_analysis_db()
                return HttpResponse(result)
            # 根据输入内容自动补全信息，返回股票代码列表和股票名称列表
            if (request.GET.get("cmd_class") == "search"):
                if (request.GET.get("command") == "search_stockname"):
                    search_txt = request.GET.get("search_txt")
                    namelist, tscodelist = index_search.searchinput_autofill(search_txt)
                    return JsonResponse((namelist, tscodelist), safe=False)

    return render(request, 'stock/index.html', )


@check_login
def index_query(request):
    """
    index页面查询信息功能
    :param request:
    :return:
    """
    if request.is_ajax():
        if (request.GET.get("cmd_class") == "query"):
            cmd = request.GET.get("command")
            stockname = request.GET.get("stockname")
            if (cmd == 'daily'):
                data = index_search.query_daily_by_stockname(stockname)
                columns = index_search.query_table_columns_chsname(global_variable.DAILY_TABLE)
                return JsonResponse({'columns': columns, 'data': data}, safe=False)
            if (cmd == 'daily_basic'):
                data = index_search.query_daily_basic_by_stockname(stockname)
                columns = index_search.query_table_columns_chsname(global_variable.DAILY_BASIC_TABLE)
                return JsonResponse({'columns': columns, 'data': data}, safe=False)
            if (cmd == 'block_trade'):
                data = index_search.query_block_trade_by_stockname(stockname)
                columns = index_search.query_table_columns_chsname(global_variable.BLOCK_TRADE_TABLE)
                return JsonResponse({'columns': columns, 'data': data}, safe=False)
            if (cmd == 'moneyflow'):
                data = index_search.query_moneyflow_by_stockname(stockname)
                columns = index_search.query_table_columns_chsname(global_variable.MONEYFLOW_TABLE)
                return JsonResponse({'columns': columns, 'data': data}, safe=False)
    return render(request, 'stock/index.html')


@check_login
def analysis(request):
    if ((request.method == "GET") and (request.is_ajax())):

        if (request.GET.get("cmd_class") == "query"):
            # 按资金流量快捷查询
            if (request.GET.get("command") == "money_inflow"):
                days = request.GET.get("continuedays")
                in_or_out = request.GET.get("in_or_out")
                query_ts_code = request.GET.get("query_code_list")
                query_ts_code = simplejson.loads(query_ts_code)
                ts_code_list, name_list = ana.quick_select_stock_by_flow(days, in_or_out, query_ts_code)

                return JsonResponse((ts_code_list, name_list), safe=False)
            # 按涨跌快捷查询
            if (request.GET.get("command") == "by_updown"):
                days = request.GET.get("continuedays")
                updown = request.GET.get("updown")
                query_ts_code = request.GET.get("query_code_list")
                query_ts_code = simplejson.loads(query_ts_code)
                ts_code_list, name_list = ana.quick_select_stock_by_updown(days, updown, query_ts_code)

                return JsonResponse((ts_code_list, name_list), safe=False)
            # 按涨幅快捷查询
            if (request.GET.get("command") == "by_pct_chg"):
                days = request.GET.get("continuedays")
                updown = request.GET.get("updown")
                pct_chg = request.GET.get("pct_chg")
                query_ts_code = request.GET.get("query_code_list")
                query_ts_code = simplejson.loads(query_ts_code)
                ts_code_list, name_list = ana.quick_select_stock_by_pct_chg(days, updown, pct_chg, query_ts_code)

                return JsonResponse((ts_code_list, name_list), safe=False)

            # 按条件查询
            if (request.GET.get("command") == "query_with_conditions"):
                dic_conditions_list = request.GET.get("data")  # 返回一个字符串
                dic_con = simplejson.loads(dic_conditions_list)  # 解析字符串，返回一个list
                query_trade_date = request.GET.get("trade_date")
                ts_code_list, name_list = ana.query_stock_with_conditons(query_trade_date, dic_con)

                return JsonResponse((ts_code_list, name_list), safe=False)
    if ((request.method == "POST") and (request.is_ajax())):
        if (request.POST.get("cmd_class") == "write_db"):
            # 添加关注数据
            if (request.POST.get("command") == "attention_code"):
                attention_code = request.POST.get("data")
                attention_code = simplejson.loads(attention_code)
                trade_date = request.POST.get("trade_date")
                result = ana.attention_stock_into_db(trade_date, attention_code)
                return HttpResponse(result)

    return render(request, 'stock/analysis.html')


@check_login
def inner_query(request):
    """
    从新浪和东方财富获取股票图形信息
    :param request:
    :return:
    """
    if request.is_ajax():
        if (request.method == "GET"):
            cmd = request.GET.get("request_cmd")
            if (cmd == 'chart_moneyflow'):
                ts_code = request.GET.get("ts_code")
                return HttpResponse(show_detail.get_chart_moneyflow_from_eastmoney(ts_code))
            if (cmd == 'data_moneyflow'):
                ts_code = request.GET.get("ts_code")
                new_moneyflow = show_detail.get_new_moneyflow(ts_code)

                return JsonResponse(new_moneyflow, safe=False)


@check_login
def show_stock_detail(request):
    """
    股票详细信息页面
    :param request:
    :return: 返回股票详细信息页面，需要获取股票ts_code 和股票名称
    """
    if request.is_ajax():
        if (request.method == "GET"):
            stock_name = request.GET.get("stock_name")
            ts_code = request.GET.get("ts_code")
            return render(request, 'stock/show_detail.html', {"stock_name": stock_name, "ts_code": ts_code})
    stock_name = request.GET.get("stock_name")
    ts_code = request.GET.get("ts_code")
    return render(request, 'stock/show_detail.html', {"stock_name": stock_name, "ts_code": ts_code})


@check_login
def attention_stock(request):
    if request.is_ajax():
        if (request.method == "GET"):
            if (request.GET.get("command") == 'attention_data'):
                is_end = request.GET.get("is_end")
                data = att_stock.get_stock_data(is_end)
                # data = serializers.serialize("json",data)
                return JsonResponse(data, safe=False)
            if (request.GET.get("command") == 'cancel_attention'):
                ts_code_list = request.GET.get("ts_code_list")
                ts_code_list = simplejson.loads(ts_code_list)
                att_stock.update_attention_state(ts_code_list, False)  # 修改为取消关注
                return HttpResponse('ok')
            if (request.GET.get("command") == 'afresh_attention'):
                ts_code_list = request.GET.get("ts_code_list")
                ts_code_list = simplejson.loads(ts_code_list)
                att_stock.update_attention_state(ts_code_list, True)  # 修改为重新关注
                return HttpResponse('ok')
        if (request.method == "POST"):
            if (request.POST.get("command") == 'clear_attention_data'):
                is_end = request.POST.get("is_end")
                att_stock.clear_attention_date(is_end)

    return render(request, 'stock/attention_stock.html')
